﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System
{
    /// <summary>
    /// 随机权重
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class RandomV2<T>
    {
        private static readonly Random Rnd = new Random();
        private List<KeyValuePair<T, ushort>> _data;

        public RandomV2(IEnumerable<KeyValuePair<T, ushort>> data)
        {
            _data = new List<KeyValuePair<T, ushort>>(data);
        }

        public T[] Next(int count)
        {
            //临时变量
            var dict = new Dictionary<T, int>();

            //为每个项算一个随机数并乘以相应的权值
            for (int i = _data.Count - 1; i >= 0; i--)
            {
                var kv = _data[i];
                dict.Add(kv.Key, Rnd.Next(100) * kv.Value);
            }

            //排序
            var listDict = SortByValue(dict);

            //拷贝抽取权值最大的前Count项
            var result = new List<T>();
            foreach (var kvp in listDict.GetRange(0, count))
            {
                result.Add(kvp.Key);
            }
            return result.ToArray();
        }

        /// <summary>
        /// 排序集合
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        private List<KeyValuePair<T, int>> SortByValue(Dictionary<T, int> dict)
        {
            var list = new List<KeyValuePair<T, int>>();
            list.AddRange(dict);
            list.Sort((kvp1, kvp2) => kvp2.Value - kvp1.Value);
            return list;
        }
    }
}